<template>
  <view class="hb-flex hb-items-center hb-mb-4">
    <TmIcon name="ali-icon icon-privilege1" color="primary" :font-size="40" />
    <TmText class="hb-ml-2" _class="hb-font-bold" label="会员资料" :font-size="28" />
  </view>

  <TmText
    _class="hb-mb-4"
    label="从社会组织小程序授权过来的会员资料"
    color="#646566"
    :font-size="24"
  />

  <!-- 机构信息 -->
  <view
    v-if="memberInfo"
    class="hb-p-3 hb-mb-4 hb-border hb-border-solid hb-border-[#EBEDF0] hb-rounded-lg hb-flex hb-items-center"
  >
    <TmImage
      class="hb-flex-shrink-0"
      :src="memberInfo.orgLogo"
      :width="80"
      :height="80"
      :round="1"
    />
    <view class="hb-ml-3 hb-flex-1">
      <TmText _class="hb-font-bold text-overflow-1" :label="memberInfo.orgName" :font-size="32" />
    </view>
  </view>

  <view class="hb-flex hb-items-center hb-justify-between hb-mb-3">
    <TmText label="允许外部咨询会员信息" _class="hb-font-bold" :font-size="28" />
    <TmSwitch 
      text 
      barIcon="" 
      :checked="memberInfo?.enable === 1"
      @change="handleEnableChange"
    />
  </view>

  <TmText
    label="开启后，外部用户访问本智能助手对话时，可匹配获取会员信息（不包含手机号、微信号等联系信息）。"
    color="#969799"
    :font-size="24"
  />
</template>

<script lang="ts" setup>
  import { getMemberInfo, setMemberEnable } from '@/api/knowledgeBase';
  import { MemberInfoResult } from '@/api/knowledgeBase/types';

  defineOptions({
    name: 'MemberResource',
  });

  // 会员信息
  const memberInfo = ref<MemberInfoResult | null>(null);

  // 获取会员信息
  const fetchMemberInfo = async () => {
    try {
      const res = await getMemberInfo();
      memberInfo.value = res;
    } catch (error) {
      console.error('获取会员信息失败:', error);
    }
  };

  // 处理启用/禁用状态变更
  const handleEnableChange = async (checked: boolean) => {
    if (!memberInfo.value) return;
    const enable = checked ? 1 : 0;
    try {
      await setMemberEnable(enable);
      // 更新本地数据
      memberInfo.value.enable = enable;
      uni.showToast({
        title: enable ? '已启用' : '已禁用',
        icon: 'success'
      });
    } catch (error) {
      console.error('设置会员状态失败:', error);
    }
  };

  onMounted(() => {
    fetchMemberInfo();
  });
</script>

<style lang="scss" scoped>

</style>